package com.subject.shuati.domain.handler.subject;

import com.subject.shuati.common.enums.IsDeleteFlagEnum;
import com.subject.shuati.common.enums.SubjectInfoTypeEnum;
import com.subject.shuati.domain.covert.RadioSubjectConverter;
import com.subject.shuati.domain.entity.SubjectAnswerBo;
import com.subject.shuati.domain.entity.SubjectInfoBo;
import com.subject.shuati.domain.entity.SubjectOptionBo;
import com.subject.shuati.infra.basic.entity.SubjectRadio;
import com.subject.shuati.infra.basic.service.SubjectRadioService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 单选题目的策略模式实现类
 */
@Component
public class RadioTypeHandler implements SubjectTypeHandler{
    @Resource
    private SubjectRadioService subjectRadioService;

    @Override
    public SubjectInfoTypeEnum getHandlerType() {
        return SubjectInfoTypeEnum.RADIO;
    }

    @Override
    public void add(SubjectInfoBo subjectInfoBo) {
        try {
            List<SubjectRadio> subjectRadio = new ArrayList<>();
            subjectInfoBo.getOptionList().forEach(option->{
                SubjectRadio radio = RadioSubjectConverter.INSTANCE.BoConverterToEntity(option);
                radio.setSubjectId(subjectInfoBo.getId());
                radio.setIsDeleted(IsDeleteFlagEnum.UN_DELETE.getCode());
                subjectRadio.add(radio);
            });
            subjectRadioService.batchInsert(subjectRadio);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public SubjectOptionBo query(int subjectId) {
        SubjectRadio subjectRadio = new SubjectRadio();
        subjectRadio.setSubjectId(Long.valueOf(subjectId));
        List<SubjectRadio> result = subjectRadioService.queryByCondition(subjectRadio);
        List<SubjectAnswerBo> subjectAnswerBOList = RadioSubjectConverter.INSTANCE.EntityConverterToBoList(result);
        SubjectOptionBo subjectOptionBO = new SubjectOptionBo();
        subjectOptionBO.setOptionList(subjectAnswerBOList);
        return subjectOptionBO;
    }
}
